# -*- coding:utf-8 -*-
# !/usr/bin/env
# @description 测试环境数据库对象文件
# @author:jack.spanrrows
# @datetime: 2018/07/30 23:29
# @copyRight jack.spanrrows@gmail.com

import pymysql
import os, sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
DOCKER_IDC_RC = "/www/web/IDC_RC"
IDC_RC = "/var/html/IDC_RC"
IDC_ONLINE = "/www/web/IDC_ONLINE"
db = True
if os.path.isfile(DOCKER_IDC_RC) or os.path.isfile(IDC_RC):
    from scrapy_web_py3.config.testing import db
elif os.path.isfile(IDC_ONLINE):
    from scrapy_web_py3.config.online import db

class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kw):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)
        return cls._instance

class MysqlConnect(Singleton):
    _instance = None
    def __init__(self):
        self.host = db.config['database']['host']
        self.port = db.config['database']['port']
        self.uname = db.config['database']['uname']
        self.passwd = db.config['database']['passwd']
        self.dbname = db.config['database']['dbname']
        self.get_cursor()

    def get_cursor(self):
            self.conn = pymysql.connect(host=self.host, port=self.port, user=self.uname, passwd=self.passwd, db=self.dbname, charset='utf8')
            self.cursor = self.conn.cursor()

    def mysql_execute(self, sql):
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            errorMessage = "Insert db Failed!Mysql Exception:%s" % str(e)
            self.conn.rollback()
            return errorMessage
        else:
            self.mysql_close()
            return "Updates data Success!"

    def mysql_thread_execute(self, sql):
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            # self.conn.ping()
        except Exception as e:
            print(e)
            self.conn = pymysql.connect(host = self.host, port = self.port, user = self.uname, passwd = self.passwd, db = self.dbname, charset = 'utf8')
            self.cursor = self.conn.cursor()
            self.mysql_thread_execute(sql)
        else:
            # self.mysql_close()
            return self.cursor.lastrowid

    def mysql_close(self):
        self.conn.close()

    def get_fetch_one(self, sql):
        self.cursor.execute(sql)
        data = self.cursor.fetchone()
        return data

    def get_fetch_all(self, sql):
        self.mysql_execute(sql)
        data = self.cursor.fetchall()
        # self.mysql_close()
        return data

    def save_one_data(self, sql):
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            errorMessage = "Insert db Failed!Mysql Exception:%s" % str(e)
            self.conn.rollback()
            return errorMessage
        else:
            self.mysql_close()
            return self.cursor.lastrowid

def insertToDb(sql):
    try:
        mysql_db = MysqlConnect()
        return mysql_db.mysql_execute(sql)
    except Exception as e:
        return str(e)

